import { observable, toJS } from 'mobx'
import { message } from "antd"
import { history } from 'umi';
const { exec } = require('child_process');
const net = require('net')
const path = require('path');
const process = require('process');
const fs = require("fs");
const nw = require('nw.gui');

import fingerStore from "../FingerprintEntry/model"
import allocationStore from "../Allocation/model"
import assistStore from "../Assist/model"
import indexStore from "../model"
import { sys } from "@/utils/sys";

//数据类型说明
//发送扫描指纹的指令
//WEB_FINGER_SCAN
//发送进行比对的指纹命令
//WEB_FINGER_CMP
//发送设备红色灯信号
//WEB_LIGHT_RED
//发送设备绿色灯信号
//WEB_LIGHT_GREEN
//发送设备白色灯信号
//WEB_LIGHT_WHITE
//发送设备闪动灯信号
//WEB_LIGHT_FLICKER
//发送退出程序信号
//WEB_EXIT
//发送获取设备状态
//WEB_DEVICE_STATUS
//发送重新读取数据库文件
//WEB_RELOAD_DB
//设置单个指纹新加
//WEB_FINGER_ADD

//接收指纹信息
//DEVICE_FINGER_SCAN
//接收指纹比对结果
//DEVICE_FINGER_CMP
//接收设备状态
//DEVICE_STATUS
//读取文件进度
//DEVICE_READ_PROGRESS


const m = observable({
    // 用来判断是那个模块在调用
    flag: "",
    // 用来判断指纹机有无启动
    isServer: false,

    clients: [],
    serverStatus: "",
    // createServer(port = 13333) {
    // },
    createServer(port = 13333) {
        net.createServer((client => {
            m.clients.push(client);
            console.log(`新的客户端链接进来了: ${client.remoteAddress}:${client.remotePort}`);
            client.on('data', clData => {
                //console.log(data.toString(),"data__")
                //console.log(`Received data from client: ${data.toString()}`)
                m.listener(clData)

            });
            client.on('end', () => {
                const index = m.clients.indexOf(client);
                if (index !== -1) {
                    m.clients.splice(index, 1);
                }
                console.log(`正常断开链接!`);
            });
            client.on('close', function () {
                const index = m.clients.indexOf(client);
                if (index !== -1) {
                    m.clients.splice(index, 1);
                }
                console.log(`非正常断开链接!`);
            });
        })).on('error', (error) => {
            //设置5秒钟自动重新链接
            m.serverStatus = 'error';
            console.log('Error creating server:', error);
            setTimeout(() => m.createServer(), 3000);
        }).on('listening', () => {
            m.serverStatus = 'listening';
            console.log('Server is listening');
        }).on('close', () => {
            m.serverStatus = 'closed';
            console.log('Server has closed');
        }).listen(port, () => {
            console.log(`running ...`)
            m.isServer = true
        })
    },
    send(ac) {
        m.clients.forEach((c) => {
            // console.log(`send : ${c.remoteAddress}:${c.remotePort}`);
            c.write(ac + `\n`); //必须有\n
        });
    },
    WEB_FINGER_SCAN() {
        m.send(`WEB_FINGER_SCAN|1\n`);
    },
    WEB_FINGER_CMP() {
        // console.log("进入扫描了")
        //发送命令后设备进行识别指纹加查找数据库比较
        m.send(`WEB_FINGER_CMP|1\n`);
    },
    WEB_LIGHT_RED() {
        m.send(`WEB_LIGHT_RED|1\n`);
    },
    WEB_LIGHT_GREEN() {
        m.send(`WEB_LIGHT_GREEN|1\n`);
    },
    WEB_LIGHT_WHITE() {
        m.send(`WEB_LIGHT_WHITE|1\n`);
    },
    WEB_LIGHT_FLICKER() {
        m.send(`WEB_LIGHT_FLICKER|1\n`);
    },
    WEB_EXIT() {
        m.send(`WEB_EXIT|1\n`);
    },
    WEB_DEVICE_STATUS() {
        m.send(`WEB_DEVICE_STATUS|1\n`);
    },
    WEB_RELOAD_DB() {
        m.send(`WEB_RELOAD_DB|1\n`);
    },
    WEB_RELOAD_FINGER() {
        m.send(`WEB_RELOAD_FINGER|1\n`);
    },
    WEB_FINGER_ADD(userId, fingerStr) {
        //添加单个指纹信息 userId fingerStr 患者编号 指纹信息
        console.log("天加了一条==", userId)
        console.log("==========================")
        m.send(`WEB_FINGER_ADD|` + userId + `|` + fingerStr + `\n`);
    },
    WEB_READ_PROGRESS() {
        //查询获取加载的进度
        m.send(`WEB_READ_PROGRESS|1\n`);
    },
    //安装设备的驱动
    WEB_SETUP_DRIVE() {
        m.send(`WEB_SETUP_DRIVE|1\n`);
    },
    getValueByIndex(str, index) {
        const arr = str.split('|')
        if (index < arr.length) {
            return arr[index]
        } else {
            return ""
        }
    },
    listener(clData) {
        const data = clData.toString().replace(/\n/g, "")
        const ac = m.getValueByIndex(data, 0)
        if (ac == "DEVICE_FINGER_SCAN") {
            //DEVICE_FINGER_SCAN|4D8AA3A33231000004C6C40408.... 扫描到指纹
            //DEVICE_FINGER_SCAN|0 没有扫描到指纹
            // console.log("扫描到了指纹===", m.getValueByIndex(data, 1))
            let fingerStr = m.getValueByIndex(data, 1)
            // 如果扫描到指纹
            if (Number(fingerStr) !== 0) {
                fingerStore.fingerStr = fingerStr
                fingerStore.isFinger = true
            }
            return
        }
        if (ac == "DEVICE_FINGER_CMP") {
            //DEVICE_FINGER_CMP|0 比对完成没有找到指纹
            //DEVICE_FINGER_CMP|-1 没有扫描到指纹
            //DEVICE_FINGER_CMP|2|581 找打对应的患者编号2 对比分数 581
            // console.log("正在识别指纹===", data)
            let id = m.getValueByIndex(data, 1)
            let num = m.getValueByIndex(data, 2)
            // m.flag判断谁在调用
            if (m.flag === "allocation") {

                if (id != "0" && id != "-1" && num > 55) {
                    m.WEB_LIGHT_GREEN()
                    // 播放提示音频
                    indexStore.playAudio()
                    allocationStore.patientId = id
                    allocationStore.allocation()
                } else {
                    // 没有录入指纹
                    if (id == 0) {
                        // 打开nw弹框
                        allocationStore.createPopup({ isfinger: "没有录入指纹" })
                    }
                    // 停止扫描
                    if (!allocationStore.isStop) {
                        allocationStore.contrast()
                    }
                }

            } else { // 否则就是 assist 在调用

                if (id != "0" && id != "-1" && num > 55) {
                    m.WEB_LIGHT_GREEN()
                    // 播放提示音频
                    indexStore.playAudio()
                    assistStore.patientId = id
                    // 按钮激活
                    assistStore.isdisabled = false
                    assistStore.allocation()
                    assistStore.contrast()
                } else {
                    // 没有录入指纹
                    if (id == 0) {
                        assistStore.isfinger = false
                    }
                    // 停止扫描
                    if (!assistStore.isStop) {
                        assistStore.contrast()
                    }
                }

            }

            return
        }
        if (ac == "DEVICE_STATUS") {
            //DEVICE_STATUS|1 设备正常
            //DEVICE_STATUS|0 设备不正常
            //设备状态码在每次进行指纹扫描时候会更新
            console.log("指纹机状态====", data)
            let status = m.getValueByIndex(data, 1)
            if (status != 1) {
                m.WEB_RELOAD_FINGER()
            }
            return
        }
        if (ac == "DEVICE_READ_PROGRESS") {
            //DEVICE_READ_PROGRESS|100 程序加载的进度
            let state = m.getValueByIndex(data, 1)
            if (state >= 10) {
                indexStore.state = state
            }
            console.log("程序加载的进度", state)
            if (state == 100) {
                // 跳转到之前的路径
                let endPath = localStorage.getItem("endPath")
                if (endPath) {
                    history.push(endPath)
                }
            }
            return
        }
        if (ac == "DEVICE_RELOAD_FINGER") {
            //DEVICE_RELOAD_FINGER|1 加载完成设备正常
            //DEVICE_RELOAD_FINGER|0 设备不正常
            //DEVICE_RELOAD_FINGER|-1 设备不正常
            console.log("重载状态===", data)
            return
        }
        //获取驱动是否安装 需要拷贝setup.exe到nw的目录下修改为setup.dll
        if (ac == "DEVICE_SETUP_DRIVE") {
            //DEVICE_SETUP_DRIVE|1 已经安装驱动
            //DEVICE_SETUP_DRIVE|0 没有安装驱动
            console.log("setup安装状态=====", data)
            return
        }
        //单条指纹添加成功后获取的信息
        if (ac == "DEVICE_FINGER_ADD") {
            //DEVICE_FINGER_ADD|1|555565454 患者ID 添加成功的指纹
            // console.log(data, "data")
            let str = m.getValueByIndex(data, 2)
            let arr = JSON.parse(sessionStorage.getItem("dayfingerprintData"))
            if (!arr) {
                arr = []
            }
            arr.push(str)
            sessionStorage.setItem("dayfingerprintData", JSON.stringify(arr))
            return
        }
        console.log(data, "没有匹配的data")
    },
    //自我链接
    connectionServer() {
        const socket = net.createConnection({ port: 13333 })
        socket.on('data', data => {
            console.log(data.toString())
        })
    },
    //打开进程
    openExe() {
        //console.log(__dirname);
        //const path = require('path');
        //const process = require('process');
        //console.log(process.cwd()); //C:\Users\admin\Desktop\umi3\dist
        const appPath = path.dirname(process.execPath);
        //console.log(appPath);  //C:\Users\admin\Desktop\nwjs-sdk-v0.67.1-win-x64
        exec(`"` + appPath + "\\finger.dll" + `"`, (error, stdout, stderr) => {
            if (error) {
                console.log('Error: ' + error.code, error.stack);
                return;
            }
            console.log('openExe: ', stdout, stderr);
        });
    },
    //关闭进程
    closeExe() {
        exec('taskkill /im finger.dll -f', function (error, stdout, stderr) {
            console.log("关闭finger.dll")
            if (error) {
                console.log(error.stack);
                console.log('Error code: ' + error.code);
                return;
            }
            console.log('closeExe: ', stdout, stderr);
        });
    },
    addCloseConfirm() {
        nw.Window.get().on('close', () => {
            // 阻止窗口关闭
            if (confirm("确定要退出本程序吗？")) {
                // 如果关闭exe 同时关闭finger.dll子程序
                m.closeExe()
                setTimeout(() => {
                    m.closeExe()
                    //可以在这里调用关闭EXE
                    nw.Window.get().close(true)
                }, 500);

            } else {
                return false
            }
        })
    },
    writeFile(fileName, writeStr) {
        //在nw的目录下写入文件
        const appPath = path.dirname(process.execPath)
        fs.writeFile(appPath + "/" + fileName, writeStr, (err) => {
            if (err) {
                console.error(err);
            } else {
                console.log("File saved successfully.");
            }
        });
    },
    //存放下载下来的blob数据到文件 会替换源文件
    writeBlobFile(fileName, blobData) {
        const appPath = path.dirname(process.execPath)
        sys.blobToString(blobData).then(e => {
            //在nw的目录下写入文件
            fs.writeFile(appPath + "/" + fileName, e, (err) => {
                // 查看进程
                m.openExe()
                if (err) {
                    console.error(err);
                } else {
                    console.log("File blob saved successfully.");
                }
            });
        })
    },
    //删除nw下的文件
    deleteFile(fileName) {
        const appPath = path.dirname(process.execPath)
        fs.unlink(appPath + "/" + fileName, (err) => {
            if (err) {
                console.error(err);
            } else {
                console.log("File deleted successfully.");
            }
        });
    },
    //居中窗口
    centerWindow() {
        const x = Math.floor((window.screen.availWidth - window.outerWidth) / 2);
        const y = Math.floor((window.screen.availHeight - window.outerHeight) / 2);
        // window.resizeTo(window.outerWidth, window.outerHeight);
        window.moveTo(x, y);
    },
    //右下角窗口
    rightBottomWindow() {
        window.moveTo(window.screen.availWidth - window.outerWidth, window.screen.availHeight - window.outerHeight);
    },
    //设置窗口大小
    setWindowSize(width, height) {
        window.resizeTo(width, height);
    },
    minimizeWindow() {
        nw.Window.get().minimize()
    },
    restoreWindow() {
        nw.Window.get().restore()
    },
    maxWindow() {
        nw.Window.get().maximize()
    },
    // 全屏 / 退出全屏
    toggleFullscreen() {
        const nwWindow = nw.Window.get();
        if (nwWindow.isFullscreen) {      // 检测是否全屏
            nwWindow.leaveFullscreen();  // 退出全屏状态
        } else {
            nwWindow.enterFullscreen();  // 进入全屏状态
        }
    },

    testText: "开始录入",
    testTimer: 0,
    test() {
        if (!m.testTimer) {
            clearInterval(m.testTimer);
            m.testTimer = setInterval(() => {
                console.log(`在线数量:` + m.clients.length)
                m.clients.forEach((c) => {
                    console.log(`send : ${c.remoteAddress}:${c.remotePort}`)
                    c.write(`hi,this is utf-8 消息 \n`) //必须有\n
                });
            }, 1000);
            m.testText = "停止采集"
        } else {
            clearInterval(m.testTimer)
            m.testTimer = 0
            m.testText = "开始采集"
        }
    },
    // 网络错误，退出重新进入
    closeApp() {
        m.closeExe()
        setTimeout(() => {
            m.closeExe()
            //可以在这里调用关闭EXE
            nw.Window.get().close(true)
        }, 500);
    }
})

export default m